<style rel="stylesheet/scss" lang="scss" scoped>
.pds-form-item {
    display: inline-block;
    width: 33%;
}

.pds-form-textarea {
    width: 80%;
}
.col-25 {
    width: 25%;
}
.label-block {
    display: inline-block;
    width: 100%;
}
.avatar-box {
    width: 178px;
    height: 178px;
    display: block;
    border-radius: 6px;
    overflow: hidden;
    display: inline-block;
    position: relative;
    &:hover {
        .cover {
            display: block;
        }
    }
    img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    .cover {
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.2);
        position: absolute;
        left: 0;
        top: 0;
        text-align: center;
        line-height: 178px;
        display: none;
        i {
            font-size: 28px;
            color: white;
            padding: 10px;
        }
    }
}
</style>
<template>
<div class="">
  <el-form :model="ruleForm" :rules="basicFormRules" ref="ruleForm" label-width="140px">
    <el-form-item :label="$t(item.label)+'：'" v-show="!item.hidden" :prop="item.name" v-for="(item,index) in basicInfo" :key="index" :label-width="item.labelWidth||'140px'" class="pds-form-item" :class="{'pds-form-textarea':item.element=='textarea'||item.element=='upload'||item.element=='input'&&item.col==100||item.element=='checkbox'||item.element=='label-block'||item.col==100,'col-25':item.col==25}">
      <!-- {{item.name}}{{ruleForm[item.name]}} -->
      <el-input v-model="ruleForm[item.name]" v-if="item.element=='input'" :placeholder="item.placeholder||'请输入'" :type="item.type" :disabled="item.disabled" :maxlength="item.maxlength" @input="limitNum(ruleForm[item.name],item)">
        <template slot="append" v-if="item.append">{{item.append}}</template>
      </el-input>
      <el-input type="textarea" v-model="ruleForm[item.name]" v-if="item.element=='textarea'" :placeholder="item.placeholder||'请输入'" :disabled="item.disabled"></el-input>
      <el-select v-model="ruleForm[item.name]" :placeholder="item.placeholder||'请选择'" style="width:100%" v-if="item.element=='select'&&item.type!='multiple'" :disabled="item.disabled" @change="selectChange(item.name,index)">
        <el-option v-for="option in item.options" :key="option.id" :label="option[item.labelName || (lang=='en'?'labelEnUs':'labelZhCh')]" :value="option[item.value || 'value']">
        </el-option>
      </el-select>
      <el-select v-model="ruleForm[item.name]" placeholder="请选择(多选)" style="width:100%" v-if="item.element=='select'&&item.type=='multiple'" multiple collapse-tags :disabled="item.disabled">
        <el-option v-for="option in item.options" :key="option.id" :label="option[item.labelName || (lang=='en'?'labelEnUs':'labelZhCh')]" :value="option[item.value || 'id']">
        </el-option>
      </el-select>
      <!-- 筛选客户 -->
      <el-select v-model="ruleForm[item.name]" filterable remote :placeholder="item.placeholder||'请选择'" :multiple="item.isMultiple" :remote-method="getPdsCustomerByName" v-if="item.element=='selectFilter'&&item.name.indexOf('customerId')!=-1" :disabled="item.disabled"
          @change="customerSelectChange()">
        <el-option v-for="option in customerList" :key="option.id" :label="option[item.labelName || (lang=='en'?'labelEnUs':'labelZhCh')]" :value="option[item.value || 'id']">
        </el-option>
      </el-select>
      <!-- 筛选机型号 -->
      <el-select v-model="ruleForm[item.name]" filterable remote :placeholder="item.placeholder||'请选择'" :multiple="item.isMultiple" :remote-method="getPlmModelNo" v-if="item.element=='selectFilter'&&item.name.indexOf('plmModelN')!=-1" :disabled="item.disabled">
        <el-option v-for="option in plmModelNoList" :key="option" :label="option" :value="option">
        </el-option>
      </el-select>
      <el-date-picker v-model="ruleForm[item.name]" placeholder="请选择" style="width:100%" v-if="item.element=='datePicker'&&(item.type=='year'||item.type=='month')" :type="item.type" :value-format="item.format||'yyyy'">
      </el-date-picker>
      <el-date-picker v-model="ruleForm[item.name]" placeholder="请选择" style="width:100%" v-if="item.element=='datePicker'&&item.type!='year'&&item.type!='month'" value-format="yyyy-MM-dd">
      </el-date-picker>

      <el-cascader placeholder="请选择" v-if="item.element=='cascader'" :options="item.options" v-model="ruleForm[item.name]" :props="item.props || {value:'id',label:lang=='en'?'labelEnUs':'labelZhCh'}"></el-cascader>
      <!-- 销售对接人 -->
      <el-input v-if="item.element == 'departAdmin'" @focus="chooseAdmin(index)" readonly :value="showNames(item.options)"></el-input>
      <!-- 上传单个图片 产品-->
      <upload-image :imageUrls="ruleForm[item.name]" @getImages="getImages" v-if="item.element=='upload'&&ruleForm[item.name]" ref="uploadImg"></upload-image>
      <!-- 上传单个文件-->
      <upload-file @getFiles="getFiles" :uploadId="index.toString()" v-if="(item.element=='uploadFile'||item.element=='uploadFileImage')&&!ruleForm[item.fileName]" :multiple="item.multiple">上传文件</upload-file>
      <div v-if="item.element=='uploadFile'&&ruleForm[item.fileName]">
        <a :href="baseUrl + '/' + ruleForm[item.fileUrl]" class="upload-tip" target="_blank">{{ruleForm[item.fileName]}}</a>
        <el-button size="small" type="danger" @click="delFile(index)" v-if="ruleForm[item.fileName]">删除</el-button>
      </div>
      <div v-if="item.element=='uploadFileImage'&&ruleForm[item.fileName]">
        <div class="avatar-box">
          <img :src="baseUrl + '/' + ruleForm[item.fileUrl]">
          <div class="cover">
            <i class="el-icon-zoom-in" @click="previewImg(ruleForm[item.fileUrl])"></i>
            <i class="el-icon-delete" @click="delFile(index)"></i>
          </div>
        </div>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="preImgSrc" alt="">
        </el-dialog>
      </div>
      <!-- 上传单个文件结束-->
      <el-checkbox-group v-model="ruleForm[item.name]" v-if="item.element=='checkbox'" :disabled="item.disabled">
        <el-checkbox border v-for="option in item.options" :key="option.id" :label="option.id">
          {{language=='en'?option.labelEnUs:option.labelZhCh}}
        </el-checkbox>
      </el-checkbox-group>
      <el-radio-group v-model="ruleForm[item.name]" v-if="item.element=='radio'" @change="radioChange(item.name,index)" :disabled="item.disabled">
        <el-radio v-for="option in item.options" :key="option.value" :label="option.value">{{language=='en'?option.labelEnUs:option.labelZhCh}}</el-radio>
      </el-radio-group>
      <!-- <el-input v-model="ruleForm[item.elementEle.name]" v-if="item.elementEle&&item.elementEle.element=='input'" :placeholder="item.placeholder||'请选择'" :type="item.elementEle.type">
        <template slot="append" v-if="item.elementEle.append">{{item.elementEle.append}}</template>
      </el-input> -->
      <span v-if="item.element=='label-block'" class="label-block">{{item.des}}</span>
      <!-- <el-button class="filter-item" type="success" icon="search" @click="" size="small" v-if="item.element=='button'">{{item.btnText}}</el-button> -->
    </el-form-item>
  </el-form>
  <depart-admin v-model="departDialog" :multiple="departMultiple" @getAdmin="getAdmin" :admin-list="departAdminList"></depart-admin>

</div>
</template>


<script>
import {
  mapGetters
} from 'vuex';
import * as saleApi from '@/api/sale/index';
import DepartAdmin from '../DepartAdmin/index';
import * as packingApi from '@/api/packing/index';
export default {
  name: 'BasicForm',
  computed: {
    ...mapGetters(['elements', 'language'])
  },
  components: {
    DepartAdmin
  },
  watch: {
    'ruleForm.watermark'(val) {
      this.getCorrugatedNo();
    },
    'ruleForm.corrugatedSpec'(val) {
      this.getCorrugatedNo();
    }
  },
  props: {
    basicInfo: {
      type: Array,
      default: () => []
    },
    lang: {
      type: String,
      default: 'zh'
    },
    ruleForm: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      preImgSrc: null,
      dialogVisible: null,
      basicFormRules: {},
      customerList: [],
      baseUrl: process.env.BASE_FILE_URL,
      plmModelNoList: [],
      props: {
        value: 'code',
        label: this.language === 'en' ? 'nameEn' : 'nameCn'
      },
      departDialog: false,
      departIndex: null,
      departMultiple: false,
      departAdminList: []
    };
  },
  created() {
    // 设置表单验证规则
    const setBasicRules = () => {
      this.basicInfo.forEach((value, index) => {
        value.name = value.name || 'blank' + index;
        const name = value.name;
        if (value.defaultValue || value.defaultValue > -1) {
          this.$set(this.ruleForm, name, value.defaultValue);
        }
        this.basicFormRules[name] = value.rules || {
          required: value.isRequired
        };
      });
    };
    setBasicRules();
    this.getCorrugatedNo();
  },
  methods: {
    // 美工设计需求页面，彩盒材质根据水印和瓦楞显示下拉
    getCorrugatedNo() {
      if (
        this.ruleForm.watermark === undefined ||
        this.ruleForm.corrugatedSpec === undefined
      ) {
        return;
      }
      packingApi
        .getCorrugatedNo({
          isWatermark: this.ruleForm.watermark,
          corrugatedNo: this.ruleForm.corrugatedSpec
        })
        .then(res => {
          res.data.map(item => {
            item.labelZhCh = item.materialName;
            item.value = item.corrugatedNo;
          });
          this.basicInfo.map(item => {
            if (item.name === 'corrugatedNo') {
              item.options = res.data;
            }
          });
        });
    },
    // 限制输入框最多输入几位小数
    limitNum(val, item) {
      // 限制小数点后多少位
      if (item.limitNum) {
        const limit = item.limitNum - 1;
        const reg = new RegExp('^\\d+\\.?\\d{0,' + limit + '}$');
        item.maxlength = reg.test(val) ? null : val.length - 1;
        console.log('reg', reg.test(val), item);
      }
    },
    // radio组件变化时操作
    radioChange(keyName, index, val) {
      const getIndex = () => {
        let index;
        this.basicInfo.map((item, idx) => {
          if (keyName === item.name) {
            index = idx;
          }
        });
        return index;
      };
      getIndex();
      index = getIndex();
      // 货号新增页面
      if (keyName === 'barcodeType') {
        if (val > -1) {
          this.ruleForm.barcodeType = val;
        }
        const notRequired = this.ruleForm.barcodeType == 3;
        this.$set(this.basicInfo[index + 1], 'hidden', notRequired);
      }
      // 货号新增页面
      if (keyName === 'isUnderwriting') {
        if (val > -1) {
          this.ruleForm.isUnderwriting = val;
        }
        const notRequired = this.ruleForm.isUnderwriting != 1;
        this.$set(this.basicInfo[index + 1], 'hidden', notRequired);
        this.$set(this.basicInfo[index + 2], 'hidden', notRequired);
        this.$set(this.basicInfo[index + 3], 'hidden', notRequired);
        this.$set(
          this.basicFormRules.underwritingWay,
          'required', !notRequired
        );
        this.$set(
          this.basicFormRules.underwritingCountry,
          'required', !notRequired
        );
        this.$set(
          this.basicFormRules.underwritingMarket,
          'required', !notRequired
        );
        console.log('this.basicFormRules', notRequired, this.basicFormRules);
      }
      // 货号新增页面
      if (keyName === 'isAntiUv') {
        if (val > -1) {
          this.ruleForm.isAntiUv = val;
        }
        const notRequired = this.ruleForm.isAntiUv != 1;
        this.$set(this.basicInfo[index + 1], 'hidden', notRequired);
        this.$set(this.basicInfo[index + 2], 'hidden', notRequired);
        this.$set(
          this.basicFormRules.timeRequirement,
          'required', !notRequired
        );
        this.$set(
          this.basicFormRules.detailRequirements,
          'required', !notRequired
        );
      }
      // 客户新增页面-是否投保
      if (keyName === 'insured') {
        if (val > -1) {
          this.ruleForm.insured = val;
        }
        const required = this.ruleForm.insured == 1;
        this.basicInfo.map((item, index) => {
          if (item.name === 'insuredAmount') {
            this.$set(this.basicInfo[index], 'hidden', !required);
            this.$set(this.basicFormRules[item.name], 'required', required);
          }
        });
      }
      // 客户新增页面-是否合作协议
      if (keyName === 'hasCoopAgreement') {
        if (val > -1) {
          this.ruleForm.hasCoopAgreement = val;
        }
        const required = this.ruleForm.hasCoopAgreement == 1;
        this.basicInfo.map((item, index) => {
          if (
            item.name === 'coopAgreementFileId' ||
            item.name === 'agreementDate' ||
            item.name === 'agreementPeriod'
          ) {
            this.$set(this.basicInfo[index], 'hidden', !required);
            this.$set(this.basicFormRules[item.name], 'required', required);
          }
        });
      }
      // 客户新增页面-产能是否满足
      if (keyName === 'capacitySatisfied') {
        if (val > -1) {
          this.ruleForm.capacitySatisfied = val;
        }
        const required = this.ruleForm.capacitySatisfied != 1;
        this.basicInfo.map((item, index) => {
          if (item.name === 'capacityUnsatisfyReason') {
            this.$set(this.basicInfo[index], 'hidden', !required);
          }
        });
      }
    },
    selectChange(keyName, index, val) {
      // 包材美工设计-彩盒
      if (keyName === 'colorBoxType') {
        const required = this.ruleForm.colorBoxType === 1;
        this.basicInfo.map((item, index) => {
          if (
            item.name === 'boxLength' ||
            item.name === 'boxWidth' ||
            item.name === 'boxHeight'
          ) {
            this.$set(this.basicInfo[index], 'hidden', !required);
            // debugger
            this.$set(this.basicFormRules[item.name], 'required', required);
          }
          if (item.name === 'boxLengthTotal' || item.name === 'boxWidthTotal') {
            this.$set(this.basicInfo[index], 'hidden', required);
            this.$set(this.basicFormRules[item.name], 'required', !required);
          }
        });
      }
      if (keyName === 'manualColor') {
        const required = this.ruleForm.manualColor === 3;
        this.basicInfo.map((item, index) => {
          if (
            item.name === 'manualCoverPageSize' ||
            item.name === 'manualInnerPageSize' ||
            item.name === 'manualCoverPageMaterial' ||
            item.name === 'manualInnerPageMaterial'
          ) {
            this.$set(this.basicInfo[index], 'hidden', !required);
            this.$set(this.basicFormRules[item.name], 'required', required);
          }
          if (
            item.name === 'manualPageSize' ||
            item.name === 'manualMaterial'
          ) {
            this.$set(this.basicInfo[index], 'hidden', required);
            this.$set(this.basicFormRules[item.name], 'required', !required);
          }
        });
      }
    },
    // 客户筛选下拉框选项
    getPdsCustomerByName(val) {
      const page = this.$route.path === '/sale/price/add'
      if (val !== '') {
        saleApi[page ? 'getCustomerTermsByName' : 'getPdsCustomerByName']({
          customerName: val
        })
          .then(res => {
            res.data.map(row => {
              row.labelEnUs = row.shortName;
              row.labelZhCh = row.shortName;
              row.value = row.code;
            });
            this.customerList = res.data;
            console.log('customerList',this.customerList)
          });
      }
    },
    customerSelectChange() {
      if (this.$route.path === '/sale/price/add') {
        this.customerList.map(item => {
          if (item.id === this.ruleForm.customerId) {
            this.ruleForm.customerName = item.name
            this.ruleForm.paymentTermsDv = item.paymentTermsDv
            this.ruleForm.customerCode = item.code
            this.ruleForm.adjustPriceConditionDv = item.adjustPriceConditionDv
          }
        })
      }
      console.log(this.ruleForm)
    },
    // 机型号筛选下拉框选项
    getPlmModelNo(val) {
      if (val !== '') {
        if(this.$route.path === '/packing/require/add/designStructure' || this.$route.path === '/packing/require/edit/designStructure' ) {
          if(this.ruleForm.pdsConfCategoryArray.length ===3) {
            packingApi.getPlmModelNoByCategoryId({
            plmModelNo: val,
            categoryId: this.ruleForm.pdsConfCategoryArray[2]
          }).then(res => {
            this.plmModelNoList = res.data;
          });
          }
        } else {
          packingApi.getPlmModelNo({
          plmModelNo: val
        }).then(res => {
          this.plmModelNoList = res.data;
        });

        }

      }
    },
    /* 显示用户名称 */
    showNames(list) {
      const nameArr = [];
      list.map(item => {
        nameArr.push(item.name);
      });
      return nameArr.join(',');
    },
    // 打开选择用户弹窗
    chooseAdmin(index) {
      this.departIndex = index;
      this.departAdminList = this.basicInfo[this.departIndex].options;
      this.departMultiple = this.basicInfo[this.departIndex].multiple;
      this.departDialog = true;
    },
    // 获取选择用户列表
    getAdmin(adminList) {
      const idList = [];
      adminList.map(item => {
        idList.push(item.id);
      });
      this.ruleForm[this.basicInfo[this.departIndex].name] = idList.join(',');
      this.basicInfo[this.departIndex].options = adminList;
    },
    // 获取上传图片
    getImages(files) {
      // debugger
      if (files.length > 0) {
        const fileIds = files.map(file => file.id);
        console.log(fileIds);
      }
      files.map(row => {
        if (row.relativeUrl) {
          row.picUrl = row.relativeUrl;
        }
      });
      this.imgList = files;
      this.ruleForm.pdsFileModelPbsPicsList = files;
    },
    // 获取上传文件
    getFiles(files, uploadId) {
      const uploadFile = files[0];
      const fileIdAttr = this.basicInfo[uploadId].name;
      console.log('fileIdAttr', fileIdAttr)
      const fileNameAttr = this.basicInfo[uploadId].fileName;
      const fileUrlAttr = this.basicInfo[uploadId].fileUrl;
      this.$set(this.ruleForm, fileIdAttr, uploadFile.id);
      this.$set(this.ruleForm, fileNameAttr, uploadFile.fileName);
      this.$set(this.ruleForm, fileUrlAttr, uploadFile.fileUrl);
    },
    previewImg(src) {
      this.dialogVisible = true
      this.preImgSrc = this.baseUrl + '/' + src
    },
    delFile(uploadId) {
      this.$confirm('是否确认删除该文件？', '提示', {
        type: 'warning'
      })
        .then(() => {
          const fileIdAttr = this.basicInfo[uploadId].name;
          const fileNameAttr = this.basicInfo[uploadId].fileName;
          const fileUrlAttr = this.basicInfo[uploadId].fileUrl;
          this.ruleForm[fileIdAttr] = null;
          this.ruleForm[fileNameAttr] = null;
          this.ruleForm[fileUrlAttr] = null;
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    // 提交表单
    submitForm() {
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate(valid => {
          resolve(valid);
        });
      });
    }
  }
};
</script>
